<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/5/28
 * Time: 16:00
 */

namespace app\admin\logic;


use app\admin\logic\code\ErrorCode;
use app\common\model\City;

class CityLogic extends BaseLogic
{

    private $cityModel;

    public function __construct()
    {
        parent::__construct();
        $this->cityModel = new City();
    }

    public function regionInfo($id){
        $regionInfo = $this->cityModel->get($id, 'region');
        if ($regionInfo){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $regionInfo);
        } else{
            return ajaxArr(ErrorCode::$INFONULL, '该信息不存在');
        }
    }

    /**
     * 地区列表
     * @param $tempWhere
     * @param $nowPage
     */
    public function regionList($tempWhere, $nowPage){
        if (is_numeric($tempWhere['status'])){
            $where[] = ['status', '=', $tempWhere['status']];
        }
        if ($tempWhere['region_name']){
            $where[] = ['name', 'like', "%".$tempWhere['region_name']."%"];
        }
        $count = $this->cityModel->where($where)->count();
        if ($count > 0){
            $regionList = $this->cityModel->where($where)->page($nowPage, self::$pageNum)->select();
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $regionList, $count);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }

    public function handle($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        switch ($act){
            case 'add':
                $res = $this->cityModel->allowField(true)->save($data);
                break;
            case 'edit':
                if ($data['status']){
                    $data['status'] = 1;
                } else{
                    $data['status'] = 0;
                }
                $res = $this->cityModel->allowField(true)->save($data,['id' => $data['id']]);
                break;
            case 'del':
                $region = $this->cityModel->get($data['id']);
                $res = $region->delete();
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        } else{
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

    public static function cityList(){
        $where[] = ['pid', '<>', 0];
        $where[] = ['status', '=', 1];
        $cityList = City::where($where)->select();
        if ($cityList){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $cityList);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '开通城市列表为空');
        }
    }

}